package me.xuym.crawler.simpleextension.processor;

import com.cbs.java.component.application.Application;
import com.cbs.java.component.database.mysql.MySqlDatabase;

import java.io.IOException;
import java.util.Map;

/**
 * Created by broche on 09/09/2017.
 */
public class SimpleResourceUpdateMySQLListProcessor extends SimpleResourceUpdateListProcessor {
    private MySqlDatabase database;
    private String table;
    private boolean debug = false;

    public SimpleResourceUpdateMySQLListProcessor(Application application, String host, String port, String username, String password, String database, String table) throws IOException, ClassNotFoundException {
        super(application);

        this.database = new MySqlDatabase(host, port, username, password, database);
        this.table = table;
    }

    public boolean isDebug() {
        return debug;
    }

    public SimpleResourceUpdateMySQLListProcessor setDebug(boolean debug) {
        this.debug = debug;
        return this;
    }

    @Override
    protected void updateResource(Map<String, String> keys, Map<String, String> values) {
        if (keys == null || keys.size() == 0) {
            return;
        }
        if (values == null || values.size() == 0) {
            return;
        }

        StringBuilder valuestr = new StringBuilder();
        for (String vk : values.keySet()) {
            String vv = values.get(vk);
            valuestr.append(String.format("%s=\"%s\",", vk, vv));
        }
        valuestr.deleteCharAt(valuestr.length() - 1);

        StringBuilder keystr = new StringBuilder();
        for (String kk : keys.keySet()) {
            String kv = keys.get(kk);
            keystr.append(String.format("and %s=\"%s\" ", kk, kv));
        }

        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(table)
                .append(" set ").append(valuestr)
                .append(" where 1=1 ").append(keystr);
        if (isDebug()) {
            System.out.println(sql.toString());
        }
        database.update(sql.toString());
    }
}
